/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: PriorityProducer
 * Author:   cakin
 * Date:     2020/5/11
 * Description: 优先级队列——生产者
 */
package com.rabbitmq.priority;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.util.ConnectionUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import static com.rabbitmq.common.Constant.NUM2;
import static com.rabbitmq.common.Constant.NUM5;
import static com.rabbitmq.common.Constant.NUM10;


/**
 * @ClassName: PriorityProducer
 * @Description: 优先级队列——生产者
 * @Date: 2020/5/11
 * @Author: cakin
 */
public class PriorityProducer {
    public static void main( String[] args ) {
        try {
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();

            // 声明交换器
            channel.exchangeDeclare("exchange_priority", "direct", true);

            // 创建优先级队列
            Map<String, Object> arg = new HashMap<String, Object>();
            arg.put("x-max-priority", NUM10);
            channel.queueDeclare("queue_priority", true, false, false, arg);
            channel.queueBind("queue_priority", "exchange_priority", "rk_priority");

            // 发送带有优先级的消息
            for (int i = 0; i < NUM10; i++) {
                AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
                if (i % NUM2 != 0) {
                    builder.priority(NUM5);
                }
                AMQP.BasicProperties properties = builder.build();
                channel.basicPublish("exchange_priority", "rk_priority", properties, ("messages-" + i).getBytes());
            }

            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
